package com.union.vehicleassistant.module.service;

import android.app.Service;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.BusUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.union.vehicleassistant.common.Constant;
import com.union.vehicleassistant.util.BlueToothUtil;
import com.union.vehicleassistant.util.SettingUtils;

/**
 * 蓝牙连接服务，可监听蓝牙连接状态
 */
public class BlueToothService extends Service {


    public static final String KEY_BLE_MAC = "KEY_BLE_MAC";
    public BleDevice connectedDevice = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 2025/1/20 绑定的服务，在这里处理业务逻辑
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        connectBleDevice();
        return START_STICKY;
    }

    /**
     * 链接蓝牙设备
     */
    private void connectBleDevice() {
        String mac = SettingUtils.getInstance().getConnectBluetoothMac();
        if (TextUtils.isEmpty(mac)) {
            BusUtils.post(Constant.BUS_KEY_BLE_NO_BLE);
            return;
        }

        boolean connected = BleManager.getInstance().isConnected(mac);
        if (connected) {
            BleDevice bleDevice = BlueToothUtil.getBleDevice(mac);
            BusUtils.post(Constant.BUS_KEY_BLE_SUCCESS, bleDevice);
            return;
        }

        BleManager.getInstance().connect(mac, new BleGattCallback() {
            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                BusUtils.post(Constant.BUS_KEY_BLE_FAIL);
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                connectedDevice = bleDevice;
                SettingUtils.getInstance().setConnectBleMac(bleDevice.getMac());
                BusUtils.post(Constant.BUS_KEY_BLE_SUCCESS, bleDevice);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                BusUtils.post(Constant.BUS_KEY_BLE_DISCONNECT);
            }
        });
    }


    @Override
    public void onDestroy() {
        releaseBle();
        super.onDestroy();
    }


    /**
     * 释放资源
     */
    private void releaseBle() {
        if (null != connectedDevice) {
            boolean connected = BleManager.getInstance().isConnected(connectedDevice);
            if (connected) {
                BleManager.getInstance().disconnect(connectedDevice);
            }
        }
    }
}
